/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package viewer.mortgage;

/**
 *
 * @author karakots
 */

import java.awt.Point;
import java.awt.Graphics;
import java.awt.Color;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

import Bank.LendingPolicy;
import Bank.Bank;

import viewer.common.Trans2D;

public class BankMCView extends MCMapObj {
   // knows how to draw bank
    final Bank bank;
    boolean statusDialogOpen;
    JDialog dialog;
    JLabel infoDialogLabel;
    JLabel logLabel;
    static int numWindows;
    BankParams bp;
    boolean haveShownFailDialog;
    HomeHistory bankLog;
    
        // constructor
    public BankMCView (Bank b, Trans2D trans) {
        this.bank = b;
        setMapImageRect(bank.getLoc().getX(), bank.getLoc().getY(), trans);
        statusDialogOpen = false;
        numWindows = 0;
        haveShownFailDialog = false;
     }

    public void drawMapImage(Graphics g, double scale) {
       if (bank.getSelected()) {
           drawBank(g, scale, IconColor.kRed);
           drawName(g, bank.name);
       }
       else {
           if (bank.getFailed())
               drawBankFail(g, scale);
           else {
                if (bank.getHasAdapted())
                    drawBank(g, scale, IconColor.kBlue);
                else
                    drawBank(g, scale, IconColor.kGreen);
           }
       }
       //drawBank(g, scale, IconColor.kGreen);
       //if (bank.getFailed())
       //    drawRedX(g, scale);

       

        if (statusDialogOpen) {
            String infoString = CreateInfoString();
            if ((infoDialogLabel == null) || (infoString == null)) {
                boolean wawaoo = true;
            } else {
                infoDialogLabel.setText(infoString);
                if (bank.nameChanged) {
                    dialog.setTitle(bank.name);
                    bank.nameChanged = false;
                }
            }
        }

       
        if (bank.getLogViewOpen()) {
            String logStr = CreateBankLogString();
            if (logLabel != null)
                logLabel.setText(logStr);
            else {
                boolean wawaoo = true;
            }
        }
       
       //if (bank.getFailed() && !haveShownFailDialog) {
       //    haveShownFailDialog = true;
       //    showFailDialog();
       //}
    }

    
    public String CreateBankLogString() {
        String labelText = new String ("<html><p align=left><b>" + "Bank Log</b><br><hr/>");

        for(String s : bank.policyRecord) {
            labelText = labelText.concat(s + "<br>");
        }
        return labelText;
    }
    

    private void showFailDialog() {
        final JFrame frame = new JFrame("Fail");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create the dialog.
        final JDialog failDialog = new JDialog(frame, bank.name);
        //a nice tan background
        failDialog.setBackground(new Color(0.8235f, 1.0f, 0.8275f));

        //Add contents to it.
        boolean wawaoo = false;
        if (bank.getAcquirer() == null) {
            wawaoo = true;
        }
        String failString = "";
        if(!wawaoo)
        {
            failString = new String("<html><p align=center>" + bank.name + " has failed." +
                " Loans, deposits and cash have been transferred to " + bank.getAcquirer().getName() + ".");
        }
        else
        {
                failString = new String("<html><p align=center>" + bank.name + " has failed." +
                " No acquirer could be found.");
        }
        JLabel failLabel = new JLabel(failString);
        failLabel.setHorizontalAlignment(JLabel.CENTER);
        failDialog.setFont(failLabel.getFont().deriveFont(Font.PLAIN,16.0f));

        //It must have a close button,
        //since some L&Fs (notably Java/Metal) don't provide one
        //in the window decorations for dialogs.
        JButton closeButton = new JButton("Close");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                failDialog.setVisible(false);
                failDialog.dispose();
            }
        });

        JPanel closePanel = new JPanel();
        closePanel.setLayout(new BoxLayout(closePanel,BoxLayout.LINE_AXIS));
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(closeButton);
        closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(failLabel, BorderLayout.CENTER);
        contentPane.add(closePanel, BorderLayout.PAGE_END);
        failDialog.setContentPane(contentPane);

        //Show it.
        int width = 200;
        int height = 200;
        failDialog.setSize(new Dimension(width, height));
        failDialog.setLocationRelativeTo(frame);
        failDialog.setVisible(true);
    }


    public boolean hit(Point p, double scale, boolean multipleSelected, boolean allSelected) {
        boolean selected;
        boolean wasSelected = bank.getSelected();
        int size =  (int) (12/scale + 0.5);
        if (bank.remotelySelectedCount > 0)
            selected = true;
        else if (multipleSelected && bank.getSelected()) {
            if (checkHit(p, size))
                bank.setSelected(!bank.getSelected());
            selected = bank.getSelected();
        } else {
           selected = checkHit(p, size);
           bank.setSelected(selected);
        }
        if(selected || allSelected) {
            if (dialog != null)
                dialog = null;
            CreateInfoWindow();
        }
        // draw links to all HH that have mortgages at this bank

        return selected;
    }

    public String CreateInfoString() {
        int cash = (int) bank.getCashAssets();
        int deposits = (int) bank.getDeposits();
        LendingPolicy lp = bank.getLendingPolicy();
        //int loans = (int) bank.;
        int reserves = (int) bank.getReserveRequired();
        int loanBalanceOutstanding = (int)bank.getLoanBalanceOutstanding();
        int numLoansFunded = (int) bank.getNumLoansCurrentlyFunded();
        int loansPreapproved = (int) bank.getLoansPreapproved();
        int numDefaults = (int) bank.getNumDefaults();
        int equity = (int) bank.getEquity();
        double pctLoansRejectedLTI = lp.getPctRejectedLTI();
        double pctLoansRejectedPctDown = lp.getPctRejectedPctDown();
        double pctLoansRejectedTooSmall = lp.getPctRejectedLoanTooSmall();
        double pctLoansRejectedTooLarge = lp.getPctRejectedLoanTooLarge();
        double pctLoanAppsAccepted;
        pctLoanAppsAccepted = 100 - (pctLoansRejectedLTI + pctLoansRejectedPctDown +
                    pctLoansRejectedTooSmall + pctLoansRejectedTooLarge);
        String pctLoansRejectedLTIStr = String.format("%2.0f",pctLoansRejectedLTI);
        String pctLoansRejectedPctDownStr = String.format("%2.0f",pctLoansRejectedPctDown);
        String pctLoansRejectedTooSmallStr = String.format("%2.0f",pctLoansRejectedTooSmall);
        String pctLoansRejectedTooLargeStr = String.format("%2.0f",pctLoansRejectedTooLarge);
        String pctLoansAcceptedStr = String.format("%2.0f",pctLoanAppsAccepted);
        int availableToLoan = (int) bank.getAmountAvialableToLoanExcludingOffers();
        String labelText = new String(
                "<html><p align=left><b>" + "Bank Info</b><br><hr/>" +
                "<html><p align=right>" +
                "Deposits = $" + deposits/1000 + "K<br>" +
                "Amount on Loan = $" + loanBalanceOutstanding/1000 + "K<br>" +
                "Amt. Preapproved = $" + loansPreapproved/1000 + "K<br>" +
                "Cash = $" + cash/1000 + "K<br>" +
                "Required Reserves = $" + reserves/1000 + "K<br>" +
                "Available to Loan =$" + availableToLoan/1000 + "K<br>" +
                "<b>Equity = $" + equity/1000 + "K</b><br>" +
                "<br>" + "<html><p align=left>" +
                lp.getNumLoansCurrentlyOnOffer() + " Loan Offers Out" + "<br>" +
                lp.getNumLoansCurrentlyPreApproved() + " Loans Pre-Approved" + "<br>" +
                numLoansFunded + " Loans Funded" + "<br>" +
                numDefaults + " Loans Defaulted" + "<br>" +
                pctLoansAcceptedStr + "% of Loan Apps Qualify"+ "<br>" +
                pctLoansRejectedTooSmallStr + "% Amt. to Borrow Too Low"+ "<br>" +
                pctLoansRejectedTooLargeStr + "% Amt. to Borrow Too High"+ "<br>" +
                pctLoansRejectedLTIStr + "% Income Too Low"+ "<br>" +
                pctLoansRejectedPctDownStr + "% Down Payment Too Low"+ "<br>" +
                "<br>");

        if (lp.fixedRateLoans)
            labelText = labelText.concat("Fixed Rate Loans<br>");
        else
            labelText = labelText.concat("Variable Rate Loans<br>");
        double loanRate = 100 * 12 * lp.monthlyMortgageInterestRate;
        String loanRateStr = String.format("%10.2f",loanRate);
        double savingsRate = 100 * 12 * bank.getSavingsMonthlyInterestRate();
        String savingsRateStr = String.format("%10.2f",savingsRate);
        int pctDown = (int) (100 * lp.minMortgagePctDown);
        int maxLTI = (int) (lp.maxPaymentToIncome*100);
        String poinstStr = String.format("%10.2f",(lp.mortgagePoints * 100));
        int maxLoanSize = ((int) lp.maxLoanSize)/1000;
        int minLoanSize = ((int) lp.minLoanSize)/1000;

        if (lp.loanLength15years && lp.loanLength30years)
            labelText = labelText.concat("15 and 30 year loans<br>");
        else if (lp.loanLength15years)
            labelText = labelText.concat("15 year loans<br>");
        else if (lp.loanLength15years)
            labelText = labelText.concat("30 year loans<br>");
        else
            labelText = labelText.concat("Yes we have no bananas<br>");
        
        labelText = labelText.concat(
                "Loan Int. Rate = " + loanRateStr + "%<br>" +
                "Savings Int. Rate = " + savingsRateStr + "%<br>" +
                "Points = " + poinstStr + "%<br>" +
                "Min Down Payment = " + pctDown + "%<br>" +
                "Min Loan Size = $" + minLoanSize + "K<br>" +
                "Max Loan Size = $" + maxLoanSize + "K<br>" +
                "Max Payment/Income = " + maxLTI + "%"
                );
        return labelText;
    }

    public void CreateInfoWindow() {
        statusDialogOpen = true;
        numWindows++;
        final JFrame frame = new JFrame("DialogDemo");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);//       .EXIT_ON_CLOSE);
        //Create the dialog.
        dialog = new JDialog(frame, bank.name);
        //a nice tan background
        dialog.setBackground(new Color(0.8235f, 1.0f, 0.8275f));

        //Add contents to it.
        infoDialogLabel = new JLabel(CreateInfoString());
        infoDialogLabel.setHorizontalAlignment(JLabel.CENTER);
        infoDialogLabel.setFont(infoDialogLabel.getFont().deriveFont(Font.PLAIN,10.0f));

        //It must have a close button,
        //since some L&Fs (notably Java/Metal) don't provide one
        //in the window decorations for dialogs.
        JButton closeButton = new JButton("Close");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (bank.getLogViewOpen()) {
                    bankLog.setVisible(false);
                    bankLog.dispose();
                    bankLog = null;
                    bank.setLogViewOpen(false);
                }
                if (bank.paramViewOpen) {
                    bp.setVisible(false);
                    bp.dispose();
                    bp = null;
                    bank.paramViewOpen = false;
                }
                dialog.setVisible(false);
                dialog.dispose();
                dialog = null;
                statusDialogOpen = false;
                numWindows--;
            }
        });
        JButton paramButton = new JButton("Params");
        paramButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!bank.paramViewOpen) {
                    bp = new BankParams();
                    bp.setTitle(bank.name);
                    bp.setBank(bank);
                    bp.setLocationRelativeTo(frame);
                    bp.setVisible(true);
                    bp.setBackground(new Color(0.8235f, 1.0f, 0.8275f));
                    bank.paramViewOpen = true;
                }
            }
        });
        
        JButton logButton = new JButton("Log");
        logButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!bank.getLogViewOpen()) {
                    bankLog = new HomeHistory();
                    bankLog.bank = bank;
                    String titleStr = new String(bank.getName());
                    bankLog.setTitle(titleStr);
                    bankLog.setLocationRelativeTo(frame);
                    bankLog.setVisible(true);
                    bankLog.setBackground(new Color(0.8235f, 1.0f, 0.8275f));
                    bank.setLogViewOpen(true);
                    logLabel = bankLog.logLabel;
                }
            }
        });
        


        JPanel closePanel = new JPanel();
        closePanel.setLayout(new BoxLayout(closePanel,BoxLayout.LINE_AXIS));
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(paramButton);
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(logButton);
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(closeButton);
        closePanel.add(Box.createHorizontalGlue());
        closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(infoDialogLabel, BorderLayout.CENTER);
        contentPane.add(closePanel, BorderLayout.PAGE_END);
        dialog.setContentPane(contentPane);

        //Show it.
        int width = 260;
        int height = 440;
        dialog.setSize(new Dimension(width, height));
        dialog.setLocationRelativeTo(frame);
        // make each one a bit offset from the others
        /*
        Point dLoc = dialog.getLocation();
        double offset;
        offset = -50 + 100*Math.random();
        dLoc.x = (int) (dLoc.getX() + offset);
        offset = -50 + 100*Math.random();
        dLoc.y = (int) (dLoc.getY() + offset);
        */
        Point dLoc = new Point(660+width*((numWindows-1)%5),0+(height+20)*((numWindows-1)/5));
        dialog.setLocation(dLoc);
        dialog.setVisible(true);
    }

}
